package br.schindler.games.android.gl.base;

import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.util.Log;
import br.schindler.games.android.gl.base.glut.GLUTUtils;

public class GLBackground implements GLDrawable {

	private int mBitmap;
	
	private FloatBuffer mTextureBuffer;
	
	private FloatBuffer mVerticesBuffer = null;
	
	private ShortBuffer mIndicesBuffer = null;
	
	private GLTextures t;
	
	private Context   ct;
	
	// The number of indices.
	private int mNumOfIndices = -1;

	/**
	 * 
	 * @param c
	 * @param id
	 */
	public GLBackground(Context c, int id) {
		this.mBitmap = (id);
		ct =c;
	}

	/*
	 * (non-Javadoc)
	 * @see br.schindler.games.android.gl.base.GLDrawable#drawFrame(javax.microedition.khronos.opengles.GL10)
	 */
	@Override
	public void drawFrame(GL10 gl) {
		gl.glPushMatrix();
		gl.glLoadIdentity();
		gl.glTranslatef(0.0f, 0.0f,-28f);
		
		gl.glDisable(GL10.GL_DEPTH_TEST);
		gl.glEnable(GL10.GL_TEXTURE_2D);
		   
		 // Set the face rotation
		//gl.glFrontFace(GL10.GL_CW);

		// Enable the texture state
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		t.setTexture(mBitmap);
		
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVerticesBuffer);		
		gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);		
		
		gl.glDrawElements(GL10.GL_TRIANGLES, mNumOfIndices, GL10.GL_UNSIGNED_SHORT, mIndicesBuffer);
		
		gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glDisable(GL10.GL_TEXTURE_2D);
		gl.glEnable(GL10.GL_DEPTH_TEST);
		gl.glPopMatrix();
	}

	/*
	 * (non-Javadoc)
	 * @see br.schindler.games.android.gl.base.GLDrawable#setAngles(float, float, float)
	 */
	@Override
	public void setAngles(float x, float y, float z) {
	}

	/*
	 * (non-Javadoc)
	 * @see br.schindler.games.android.gl.base.GLDrawable#init(javax.microedition.khronos.opengles.GL10, float, float)
	 */
	@Override
	public void init(GL10 gl, float w, float h) {
		
		float textureCoordinates[] = {
				0f, 1f,
                0f, 0f,
                1f, 1f,
                1f, 0f };
		
	    float r = w / Math.max(1,h);
		
	    w=30*r;
	    h=30;
	    
		float planeCoordinates [] = 
			 { -w/2, - h/2,  0.0f,  //v1
			   -w/2f,  h/2f, 0.0f,  //v2
                w/2f, -h/2f, 0.0f,  //v3
                w/2f,  h/2f, 0.0f };//v4
		// v1 v2 v3 / v3 v2 v4
		short[] indices = new short[] { 0, 1, 2, 2, 1, 3 };

	    t = new GLTextures(gl, ct);
	    t.add(this.mBitmap);
	    t.loadTextures();
	    
	    Log.d("GLB", "TXT LOADED");
		
		/**
		 * UV mapping
		 */
		mTextureBuffer  = GLUTUtils.toFloatBufferPositionZero(textureCoordinates);
		mVerticesBuffer = GLUTUtils.toFloatBufferPositionZero(planeCoordinates);
		mIndicesBuffer  = GLUTUtils.toShortBuffer(indices);
		mNumOfIndices   = indices.length;		
	}
}
